package com.pdool.game.msg;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Parser;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.nio.ByteBuffer;

public class MsgTask implements Runnable {

    WebSocketSession session;
    BinaryMessage message;

    public MsgTask(WebSocketSession session, BinaryMessage message) {
        this.session = session;
        this.message = message;
    }

    @Override
    public void run() {
        try {
            ByteBuffer payload = message.getPayload();
            int msgId = payload.getInt();

            MsgHandlerItem msgHandlerItem = MsgMgr.getHandlerMap().get(msgId);
            Parser in = msgHandlerItem.getIn();
            IHandler handler = msgHandlerItem.getHandler();

            byte[] dst = new byte[payload.remaining()];
            payload.get(dst);
            GeneratedMessageV3 inMsg = (GeneratedMessageV3) in.parseFrom(dst);

            GeneratedMessageV3 handle = handler.handle(session, inMsg);
            if (handle != null) {
                session.sendMessage(new BinaryMessage(handle.toByteArray()));
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}
